package com.teamclub.base.services.sendmsg;

import com.teamclub.base.confs.SmsConf;
import com.teamclub.base.forms.MessageReponse;
import com.teamclub.base.forms.SendMsgForm;
import com.teamclub.util.errors.ErrorCode;
import com.teamclub.util.libs.CheckSumBuilder;
import com.teamclub.util.libs.F;
import com.teamclub.util.libs.Json;
import com.teamclub.util.network.HTTP;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SendMsgService {
    private Logger logger = LoggerFactory.getLogger(SendMsgService.class);
    @Autowired
    private SmsConf smsConf;

    public void showSmsConf() {
        logger.info("app key : {}", smsConf.getAppkey());
    }

    public F.Either<Boolean, ErrorCode> identifyCodeSend(SendMsgForm form) {
        String nonce = String.valueOf(System.currentTimeMillis());
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(smsConf.getAppsercet(), nonce, curTime);
        HttpClient httpClient = HTTP.getRawHttpClient();
        HttpPost httpPost = new HttpPost(smsConf.getIdentifycode().getSend());
        httpPost.addHeader("AppKey", smsConf.getAppkey());
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", form.getMobile()));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            MessageReponse messageReponse = Json.fromJson(Json.parse(resp), MessageReponse.class);
            logger.info("respx: " + resp);
            if (messageReponse.getCode() == 200) {
                return F.Either.Left(true);
            } else {
                return F.Either.Right(ErrorCode.ref(messageReponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return F.Either.Right(ErrorCode.ref("发送失败"));
    }



    public F.Either<Boolean, ErrorCode> identifyCodeVerify(SendMsgForm form) {
        String nonce = String.valueOf(System.currentTimeMillis());
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(smsConf.getAppsercet(), nonce, curTime);
        HttpClient httpClient = HTTP.getRawHttpClient();
        HttpPost httpPost = new HttpPost(smsConf.getIdentifycode().getVerify());
        httpPost.addHeader("AppKey", smsConf.getAppkey());
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", form.getMobile()));
        nvps.add(new BasicNameValuePair("code", form.getCode()));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            MessageReponse messageReponse = Json.fromJson(Json.parse(resp), MessageReponse.class);
            logger.info("response is: " + messageReponse);
            if (messageReponse.getCode() == 200) {
                return F.Either.Left(true);
            } else {
                return F.Either.Right(ErrorCode.ref(messageReponse.getMsg()));
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        return F.Either.Right(ErrorCode.ref("验证失败"));
    }

    public F.Either<Boolean, ErrorCode> msgTemplatePush(SendMsgForm form) {
        String nonce = String.valueOf(System.currentTimeMillis());
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(smsConf.getAppsercet(), nonce, curTime);
        HttpClient httpClient = HTTP.getRawHttpClient();
        HttpPost httpPost = new HttpPost(smsConf.getTemplate().getSend());
        httpPost.addHeader("AppKey", smsConf.getAppkey());
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("templateid", form.getTemplateid()));
        nvps.add(new BasicNameValuePair("mobiles", form.getMobiles()));
        nvps.add(new BasicNameValuePair("params", form.getParams()));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
            MessageReponse messageReponse = Json.fromJson(Json.parse(resp), MessageReponse.class);
            logger.info("response is: " + messageReponse);
            if (messageReponse.getCode() == 200) {
                return F.Either.Left(true);
            }else{
                logger.error("短信发送异常.code:"+messageReponse.getCode()+",msg:"+messageReponse.getMsg());
                return F.Either.Right(ErrorCode.ref(messageReponse.getMsg()));

            }
        } catch (IOException e) {
            logger.error("短信发送异常", e);
            e.printStackTrace();
        }
        return F.Either.Right(ErrorCode.ref("短信发送失败"));
    }
}
